<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业/单位名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业/单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属省" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入所属省"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入所属市"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属区" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入所属区"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="detailAddress">
        <el-input
          v-model="queryParams.detailAddress"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="queryParams.customerType" placeholder="请选择客户类型" clearable>
          <el-option
            v-for="dict in dict.type.pur_supplier_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="customerLevel">
        <el-select v-model="queryParams.customerLevel" placeholder="请选择客户等级" clearable>
          <el-option
            v-for="dict in dict.type.pur_supplier_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="结算方式" prop="settlementMethod">
        <el-select v-model="queryParams.settlementMethod" placeholder="请选择结算方式" clearable>
          <el-option
            v-for="dict in dict.type.pur_supplier_ways"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:supplier:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:supplier:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:supplier:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:supplier:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商ID" align="center" prop="supplierId" />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="企业/单位名称" align="center" prop="enterpriseName" />
      <el-table-column label="所属省" align="center" prop="province" />
      <el-table-column label="所属市" align="center" prop="city" />
      <el-table-column label="所属区" align="center" prop="area" />
      <el-table-column label="详细地址" align="center" prop="detailAddress" />
      <el-table-column label="主采类目" align="center" prop="mainCategories">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_supplier_primary" :value="scope.row.mainCategories ? scope.row.mainCategories.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="照片" align="center" prop="photo" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.photo" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="客户类型" align="center" prop="customerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_supplier_type" :value="scope.row.customerType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户等级" align="center" prop="customerLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_supplier_level" :value="scope.row.customerLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="结算方式" align="center" prop="settlementMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_supplier_ways" :value="scope.row.settlementMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:supplier:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:supplier:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="企业/单位名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业/单位名称" />
        </el-form-item>
        <el-form-item label="所属省" prop="province">
          <el-input v-model="form.province" placeholder="请输入所属省" />
        </el-form-item>
        <el-form-item label="所属市" prop="city">
          <el-input v-model="form.city" placeholder="请输入所属市" />
        </el-form-item>
        <el-form-item label="所属区" prop="area">
          <el-input v-model="form.area" placeholder="请输入所属区" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="主采类目" prop="mainCategories">
          <el-checkbox-group v-model="form.mainCategories">
            <el-checkbox
              v-for="dict in dict.type.pur_supplier_primary"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
            <el-checkbox
              label="custom"
              @change="handleCustomClick">
              自定义
            </el-checkbox>
          </el-checkbox-group>
          <!-- 自定义输入框 -->
          <el-input
            v-if="showCustomInput"
            v-model="customCategory"
            placeholder="请输入自定义类目"
            style="margin-top: 10px;"
            @input="handleCustomInput"
          />
        </el-form-item>
        <el-form-item label="照片路径" prop="photo">
          <image-upload v-model="form.photo"/>
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="form.customerType" placeholder="请选择客户类型">
            <el-option
              v-for="dict in dict.type.pur_supplier_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="customerLevel">
          <el-select v-model="form.customerLevel" placeholder="请选择客户等级">
            <el-option
              v-for="dict in dict.type.pur_supplier_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算方式" prop="settlementMethod">
          <el-select v-model="form.settlementMethod" placeholder="请选择结算方式">
            <el-option
              v-for="dict in dict.type.pur_supplier_ways"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSupplier, getSupplier, delSupplier, addSupplier, updateSupplier } from "@/api/purchase/supplier"

export default {
  name: "Supplier",
  dicts: ['pur_supplier_type', 'pur_supplier_level', 'pur_supplier_ways', 'pur_supplier_primary'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      supplierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示自定义输入框
      showCustomInput: false,
      // 自定义输入值
      customCategory: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contact: null,
        phone: null,
        enterpriseName: null,
        province: null,
        city: null,
        area: null,
        detailAddress: null,
        mainCategories: null,
        customerType: null,
        customerLevel: null,
        settlementMethod: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询供应商列表 */
    getList() {
      this.loading = true
      listSupplier(this.queryParams).then(response => {
        this.supplierList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        supplierId: null,
        contact: null,
        phone: null,
        enterpriseName: null,
        province: null,
        city: null,
        area: null,
        detailAddress: null,
        mainCategories: [],
        photo: null,
        customerType: null,
        customerLevel: null,
        settlementMethod: null,
        createTime: null
      }
      this.showCustomInput = false
      this.customCategory = ''
      this.resetForm("form")
    },
    // 处理自定义选项点击
    handleCustomClick() {
      this.showCustomInput = !this.showCustomInput
      // 如果关闭自定义输入框，移除自定义值
      if (!this.showCustomInput) {
        const customIndex = this.form.mainCategories.indexOf('custom')
        if (customIndex > -1) {
          this.form.mainCategories.splice(customIndex, 1)
        }
        this.customCategory = ''
      } else {
        // 如果打开自定义输入框，添加custom标记
        if (!this.form.mainCategories.includes('custom')) {
          this.form.mainCategories.push('custom')
        }
      }
    },
    // 处理自定义值输入
    handleCustomInput() {
      // 确保custom标记在数组中
      if (!this.form.mainCategories.includes('custom')) {
        this.form.mainCategories.push('custom')
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加供应商"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const supplierId = row.supplierId || this.ids
      getSupplier(supplierId).then(response => {
        this.form = response.data
        this.form.mainCategories = this.form.mainCategories.split(",")
        // 检查是否包含自定义类别
        if (this.form.mainCategories.includes('custom')) {
          this.showCustomInput = true
          // 尝试从数据中获取自定义值
          const customValue = this.form.mainCategories.find(item => item !== 'custom' && !this.dict.type.pur_supplier_primary.some(dict => dict.value === item))
          if (customValue) {
            this.customCategory = customValue
          }
        }
        this.open = true
        this.title = "修改供应商"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理自定义类别
          if (this.showCustomInput && this.customCategory.trim()) {
            // 移除之前可能存在的自定义值
            this.form.mainCategories = this.form.mainCategories.filter(item => 
              item === 'custom' || this.dict.type.pur_supplier_primary.some(dict => dict.value === item)
            )
            // 添加新的自定义值
            this.form.mainCategories.push(this.customCategory.trim())
          }
          // 移除custom标记
          this.form.mainCategories = this.form.mainCategories.filter(item => item !== 'custom')
          this.form.mainCategories = this.form.mainCategories.join(",")
          if (this.form.supplierId != null) {
            updateSupplier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSupplier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids
      this.$modal.confirm('是否确认删除供应商编号为"' + supplierIds + '"的数据项？').then(function() {
        return delSupplier(supplierIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/supplier/export', {
        ...this.queryParams
      }, `supplier_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
